package com.cff.springbootwork.async.service;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

@Service
public class AsyncTaskService {
	private Logger log = LoggerFactory.getLogger(this.getClass());

	/**
	 * 普通的一方法而已，供异步任务调用
	 */
	public void asyncTask() {
		RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
		if (requestAttributes != null) {
			HttpServletRequest curRequest = ((ServletRequestAttributes) requestAttributes).getRequest();
			log.info("异步任务开始执行，当前请求属性test为：{}", curRequest.getAttribute("test"));
		} else {
			log.info("异步任务不是同一个线程了，别想拿ThreadLocal对象了");
		}

		try {
			Thread.sleep(5000);
			log.info("我是异步任务，我就是个打印！");
		} catch (InterruptedException e) {
			e.printStackTrace();
		}

		log.info("5s后异步任务终于执行完成");
	}
	
	@Async
	public void asyncTaskAnnotation() {
		asyncTask();
	}
}
